#include "cgzCLua.h"
#include "cgzCTcpAsioS.h"
#include "cgzCThreadPool.h"

static int asio_bind(lua_State *L)
{
    // 将其转换为 cgzCLua 指针
    cgzCLua *that = cgzCLua::getThat(L);
    const char *name = lua_tostring(L, 1);
    const char *ip = lua_tostring(L, 2);
    int port = lua_tointeger(L, 3);
    int tref = luaL_ref(L, LUA_REGISTRYINDEX);
    void *node = malloc(sizeof(cgzCTcpAsioS));
    int cid = that->getId();
    auto asioS = new (node) cgzCTcpAsioS(that->m_pool, name, ip, port, cid);
    asioS->m_tref = tref;
    asioS->tcpbind();
    return 0;
}
static int asio_send(lua_State *L)
{
    // 将其转换为 cgzCLua 指针
    cgzCLua *that = cgzCLua::getThat(L);
    const char *name = lua_tostring(L, 1);
    const int ufd = lua_tointeger(L, 2);
    const int mid = lua_tointeger(L, 3);
    size_t len = 0;
    const char *pck = lua_tolstring(L, 4, &len);
    long cid = luaL_checkinteger(L, 5);
    void *node = malloc(sizeof(cgzCSendS));
    auto psend = new (node) cgzCSendS(ufd, mid, pck, len, cid);
    that->regTask(name, psend);
    return 0;
}

int cgzCLua::luaopen_tcpAsioS(lua_State *L)
{
    static const luaL_Reg otherlib[] = {
        {"bind", asio_bind},
        {"send", asio_send},
        {NULL, NULL}};

    luaL_newlib(L, otherlib);
    return 1;
}